<template>
  <div class="library-box">
    <el-container>
      <el-header>
        <div id="header">
          <div class="logo-box">ZhebianHerb</div>
          <div class="right-box">
            <div class="title">百草库</div>
          </div>
        </div>
      </el-header>
      <el-container>
        <el-aside class="aside" :style="{ width: asideWidth + 'px' }">
          <div>
            <el-menu :default-openeds="defaultOpeneds" :collapse-transition="false" :collapse="menuCollapse"
              active-text-color="#fff" background-color="#5ba58a8b" class="el-menu-vertical-demo" default-active="2"
              text-color="#fff" router :defaultActive="defaultActive">
              <template v-for="item in menuList">
                <el-sub-menu :index="item.path" v-if="item.children" :key="item.path" class="title-one">
                  <template #title>
                    <i :class="['iconfont', item.icon]" style="width:30px; height:58px; text-align: center;"></i>
                    <span class="one-box">{{ item.menuName }}</span>
                  </template>
                  <!-- <el-sub-menu v-for="menuItem in item.children" :index="menuItem.path" :key="menuItem.path" class="title-box">
                    <template #title>
                      <span>{{ menuItem.menuName }}</span>
                    </template> -->
                  <el-sub-menu v-for="(subItem, index1) in item.children" :index="item.path + '/' + index1"
                    :key="item.path + '/' + index1" class="title-box">
                    <template #title>{{ subItem.menuName }}</template>
                    <el-menu-item v-for="(child, index2) in subItem.children"
                      :index="item.path + '/' + index1 + '/' + index2" :key="item.path + '/' + index1 + '/' + index2"
                      class="title-box">
                      {{ child.menuName }}
                    </el-menu-item>
                  </el-sub-menu>
                  <!--                      <el-menu-item v-for="subItem in item.children" :index="subItem.path" :key="subItem.path" class="title-box">-->
                  <!--                        <template #title>{{ subItem.menuName }}</template>-->
                  <!--                        <el-menu-item index="1-4-1">item one</el-menu-item>-->
                  <!--&lt;!&ndash;                        <span class="two-box">{{ subItem.menuName }}</span>&ndash;&gt;-->
                  <!--                      </el-menu-item>-->
                  <!-- </el-sub-menu> -->
                </el-sub-menu>
              </template>
            </el-menu>
          </div>
        </el-aside>
        <el-container>
          <el-header class="header-box">
            <div :class="['op-menu', 'iconfont', menuCollapse ? 'icon-expand' : 'icon-collapse',]" @click="opMenu">
            </div>
            <div class="menu-bread">
              <el-breadcrumb>
                <template v-for="item in menuBreadCrumbList">
                  <el-breadcrumb-item v-if="item.name" :key="item"
                    style="font-size: 18px; font-weight: bold; color: black;">
                    {{ item.name }}
                  </el-breadcrumb-item>
                </template>
              </el-breadcrumb>
            </div>
          </el-header>
          <el-main class="main-content">
            <div class="tag-content">
              <el-tabs v-model="defaultActive" type="card" @tab-change="tabClick" @edit="editTab" class="demo-tabs">
                <el-tab-pane v-for="item in tabList" :label="item.menuName" :name="item.path"
                  :closable="tabList.length > 1" :key="item"></el-tab-pane>
              </el-tabs>
            </div>
            <div class="content-body">
              <router-view />
            </div>
          </el-main>
        </el-container>
      </el-container>
      <el-footer>
        <Footer></Footer>
      </el-footer>
    </el-container>
  </div>
</template>

<script setup>
import { getSideBarApi } from '@/apis/news.js'
import { ref, reactive, getCurrentInstance, onMounted, watch } from "vue"
import { useRoute, useRouter } from "vue-router";

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();

//页面菜单内容
const menuList = reactive([
  {
    menuName: "纲目分类",
    icon: "icon-empty",
    path: "/library",
    children: [
      // {
      //   menuName: "草部",
      //   path: "/library/grass",
      // },
      // {
      //   menuName: "谷部",
      //   path: "/library/valley",
      // },
      // {
      //   menuName: "菜部",
      //   path: "/library/vegetable",
      // },
      // {
      //   menuName: "果部",
      //   path: "/library/fruit",
      // },
      // {
      //   menuName: "木部",
      //   path: "/library/tree",
      // },
    ]
  }

  // ,
  // {
  //   menuName: "作用分类",
  //   icon: "icon-article",
  //   path: "/library/role",
  //   children: [
  //     {
  //       menuName: "清热解毒",
  //       path: "/library/role/solve"
  //     }
  //   ]
  // }
])

const getSideBarFun = () => {
  getSideBarApi().then(res => {
    menuList[0].children = res.data
    localStorage.setItem("sider", JSON.stringify(res.data))

  })
}


// 默认选中
const defaultActive = ref('');

// 收起关闭菜单
const asideWidth = ref(250);
const menuCollapse = ref(false);
const opMenu = () => {
  menuCollapse.value = !menuCollapse.value;
  if (menuCollapse.value) {
    asideWidth.value = 63;
  } else {
    asideWidth.value = 250;
  }
};

// 默认展开的菜单
const defaultOpeneds = ref([]);

//菜单转换为map
const menuMap = {};
const init = () => {
  getSideBarFun()
  let data = JSON.parse(localStorage.getItem("sider"));

  for (let i = 0; i < data.length; i++) {
    let k = data[i].children.length
    for (let j = 0; j < k; j++) {
      let v2Path = "library/" + i + "/" + j;
      let obj = {
        path: v2Path,
        menuName: data[i].children[j].menuName
      }
      menuMap[v2Path] = obj
    }
  }
  //   设置默认选中
  router.push("/library/0/0")
  // menuList.children.forEach((item) => {
  //   defaultOpeneds.value.push(item.path);
  //   item.children.forEach((subItem) => {
  //     menuMap[subItem.path] = subItem;
  //   })
  // });
};
init();

// tabs操作
const tabList = ref([]);

const getNewPath = (path) => {
  // 获取当前路由
  let currentPath = router.currentRoute.value.path;

  // 解析当前路由
  let pathSegments = currentPath.split('/');

  let tmp = path.split("/")
  // 更换最后两级目录为 "1/1"
  pathSegments[pathSegments.length - 3] = tmp[0];
  pathSegments[pathSegments.length - 2] = tmp[1];
  pathSegments[pathSegments.length - 1] = tmp[2];

  // 构建新的路由路径
  return pathSegments.join('/');
}
const tabClick = (e) => {

  router.push(getNewPath(e));
};
const editTab = (targeKey, action) => {
  if (action !== "remove") {
    return;
  }
  let currentPath = defaultActive.value;
  let tabs = tabList.value;
  let tmpDefault = defaultActive.value.replace(/^\//, '');
  // 关闭当前选中的tab
  if (targeKey == tmpDefault) {
    tabs.forEach((tab, index) => {
      if (tab.path == targeKey) {
        let nextTab = tabs[index + 1] || tabs[index - 1];
        if (nextTab) {
          currentPath = nextTab.path;
        }
      }
    });
  }
  tabList.value = tabs.filter((tab) => {
    return tab.path !== targeKey;
  });

  let newPath = currentPath.replace(/^\//, '');
  let lastPath = getNewPath(newPath).replace(/\/$/, '')
  router.push(lastPath);
  // }
};

//面包屑导航
const menuBreadCrumbList = ref([]);

onMounted(() => {
  watch(
    () => route,
    (newVal, oldVal) => {

      defaultActive.value = route.path;
      const parts = route.path.split("/").slice(2, 4);
      let menuPath = []
      let data = JSON.parse(localStorage.getItem("sider"));
      if ( parts[0]) {
        let v1 = { index: parts[0], name: data[parts[0]].menuName, path: 'library/' + parts[0] + "/0" }
      let v2 = { index: parts[1], name: data[parts[0]].children[parts[1]].menuName, path: route.path }
      menuPath.push(v1)
      menuPath.push(v2)
      menuBreadCrumbList.value = (menuPath);
      let key = `library/${parts[0]}/${parts[1]}`
      let currentMenu = tabList.value.some((item) => {
        return item.path == key;
      });

      if (!currentMenu) {
        tabList.value.push(menuMap[key]);
      }
      }

    
    },
    { immediate: true, deep: true }
  );
});
</script>

<script>
import Footer from '@/components/Footer.vue'

export default {
  components: {
    Footer
  }
}
</script>

<style lang="scss" scoped>
.library-box {
  min-height: 100vh;
  background-image: url('@/assets/img/山楂花.png');
  background-size: cover;
  background-position: center;
}

.el-header {
  padding: 0;
}

.el-aside {
  background-color: #5ba58ad8;
  min-height: 800px;
  max-height: 850px;
}

.el-main {
  padding: 0;
  margin: 0;
}

.el-footer {
  padding: 0;
}

/* 头部 */
#header {
  /* background-color: #549b9d; */
  background-color: #5ba58ad8;
  color: #fff;
  display: flex;
  /* justify-content：项目在主轴上的对齐方式；space-between：两端对齐，项目之间的间隔都相等 */
  justify-content: space-between;
  /* 设置页面阴影 */
  box-shadow: 2px 1px 19px rgba(0, 0, 0, .1);
}

.logo-box {
  width: 200px;
  text-align: center;
  line-height: 60px;
  font-size: 22px;
  font-weight: bold;
  font-family: SimSun;
  color: #F5D3B8;
}

.right-box {
  flex: 1;
  z-index: 2;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-family: SimSun;
  font-weight: bold;
  font-size: 28px;
}

.input-box {
  width: 250px;
  height: 40px;
  display: flex;
  padding-top: 2.7%;
  align-items: center;
  justify-content: center;
}

/* 目录 */
.one-box {
  font-family: SimSun;
  font-size: 20px;
  font-weight: bolder;
}

::v-deep .title-box>.el-sub-menu__title {
  text-align: left;
  color: #F5D3B8;
  font-family: SimSun;
  font-size: 18px;
  font-weight: bold;
}

.two-box {
  color: #F5D3B8;
  font-family: SimSun;
  font-size: 18px;
  font-weight: bold;
}

/* 右边内容 */
.header-box {
  background: #fecb7fe1;
  border-bottom: 1px solid #ddd;
  height: 50px;
  /* line-height: 50px; */
  padding: 0px 10px !important;
  display: flex;
  align-items: center;
  font-family: SimSun;
}

.op-menu {
  font-size: 20px;
  cursor: pointer;
  color: #f9f9f9da;
}

.menu-bread {
  margin-left: 10px;
}

/* 内容 */
.main-box {
  width: 100%;
  height: 800px;
  background-color: #5ba58a8b;
  /* background-image: url("@/assets/img/橙色1.png"); */
  /* background-size: cover; */
  /* 设置页面阴影 */
  box-shadow: 2px 1px 19px rgba(8, 0, 0, 0.1);
}

.main-content {
  padding: 0px;

  .tag-content {
    .el-tabs--card {
      // background: linear-gradient(to bottom, #fecb7fe1, #5ba58a8b);
      background-color: #5ba58a8b;
      font-size: 32px;
      font-weight: bold;
      font-family: SimSun;
      border: none;
    }
  }

  .demo-tabs>.el-tabs__content {
    font-size: 32px;
    font-weight: bold;
    display: none;
  }

  .content-body {
    overflow: hidden;
    padding: 10px 10px 5px 10px;
    background-color: #5ba58a8b;
    height: 730px;
  }
}

::v-deep .el-tabs__item.is-active {
  background-color: #3664538b;
  color: #ffffff;
}
</style>
